import { Service } from 'egg';
import { AssuageGrief } from '../model/Assuage_grief';
import { Comment } from '../model/Comment';

class CommentService extends Service {
    /**
     * 根据解忧id获取评论列表
     * @param param 
     */
    public async searchCommentById(param: any) {
        const queryStr = `SELECT c.comment_id,c.comment_content,c.comment_status,c.comment_praise,c.comment_reply,u.user_id,u.user_avatarUrl,u.user_nickname,u.user_sex,u.user_school_year,s.school_name,s.school_badge,cl.college_name,c.created_at`
            + ` FROM t_comment c INNER JOIN t_user u ON c.assuage_grief_id = :assuage_grief_id AND c.comment_level = '1' AND c.is_shield='1' AND c.is_delete='1' AND c.user_id = u.user_id`
            + ` LEFT JOIN t_school s ON u.user_school_id = s.school_id`
            + ` LEFT JOIN t_college cl ON u.user_college_id = cl.college_id ORDER BY c.created_at ASC`;
        const resultComment: any = await this.ctx.model.query(queryStr,
            {
                type: this.ctx.model.QueryTypes.SELECT,
                replacements: { assuage_grief_id: param.assuage_grief_id }
            }
        )
        let returnData: any = [];
        for (let i = 0; i < resultComment.length; i++) {
            let item: any = {};
            item.comment_id = resultComment[i].comment_id;
            item.comment_content = resultComment[i].comment_content;
            item.comment_status = resultComment[i].comment_status;
            item.comment_praise = resultComment[i].comment_praise;
            item.comment_reply = resultComment[i].comment_reply;
            item.user_id = resultComment[i].user_id;
            item.user_avatarUrl = resultComment[i].user_avatarUrl;
            item.user_nickname = resultComment[i].user_nickname;
            item.user_sex = resultComment[i].user_sex;
            item.user_school_year = resultComment[i].user_school_year;
            item.school_name = resultComment[i].school_name;
            item.school_badge = resultComment[i].school_badge;
            item.college_name = resultComment[i].college_name;
            item.created_at = resultComment[i].created_at;
            const resultPraise = await this.ctx.service.praiseService.checkIsPraise(param.user_id, item.comment_id, '3');
            if (!resultPraise) {
                item.is_praise = '2';
            } else {
                item.is_praise = '1';
            }
            const queryStr1 = `SELECT c.comment_id,c.comment_content,c.comment_status,c.be_comment_status,u.user_id,u.user_nickname,ul.user_id AS target_user_id,ul.user_nickname AS target_user_nickname,c.created_at`
                + ` FROM t_comment c INNER JOIN t_user u ON c.assuage_grief_id = :assuage_grief_id AND c.comment_parent_id = :comment_id AND c.comment_level = '2'`
                + ` AND c.is_shield='1' AND c.is_delete = '1' AND c.user_id = u.user_id LEFT JOIN t_user ul ON c.target_user_id = ul.user_id ORDER BY c.created_at ASC`
            const resultCommentLevel2: any = await this.ctx.model.query(queryStr1,
                {
                    type: this.ctx.model.QueryTypes.SELECT,
                    replacements: { assuage_grief_id: param.assuage_grief_id, comment_id: item.comment_id }
                }
            )
            const commentList: any = [];
            for (let j = 0; j < resultCommentLevel2.length; j++) {
                const resultCommentLevel2Item: any = {};
                resultCommentLevel2Item.comment_id = resultCommentLevel2[j].comment_id;
                resultCommentLevel2Item.comment_content = resultCommentLevel2[j].comment_content;
                resultCommentLevel2Item.comment_status = resultCommentLevel2[j].comment_status;
                resultCommentLevel2Item.be_comment_status = resultCommentLevel2[j].be_comment_status;
                resultCommentLevel2Item.user_id = resultCommentLevel2[j].user_id;
                if (resultCommentLevel2[j].comment_status == 1) {
                    resultCommentLevel2Item.user_nickname = '';
                } else {
                    resultCommentLevel2Item.user_nickname = resultCommentLevel2[j].user_nickname;
                }
                resultCommentLevel2Item.target_user_id = resultCommentLevel2[j].target_user_id;
                if (resultCommentLevel2[j].be_comment_status == 1) {
                    resultCommentLevel2Item.target_user_nickname = '';
                } else {
                    resultCommentLevel2Item.target_user_nickname = resultCommentLevel2[j].target_user_nickname;
                }
                resultCommentLevel2Item.created_at = resultCommentLevel2[j].created_at;
                commentList.push(resultCommentLevel2Item);
            }

            item.commentList = commentList;
            returnData.push(item);
        }
        if (returnData.length <= 0) {
            throw new Error(JSON.stringify({ code: 2, msg: '没有数据' }));
        }
        return returnData;
    }

    /**
     * 根据解忧id获取评论列表-后台
     * @param param 
     */
    public async searchAdminCommentById(param: any) {
        const queryStr = `SELECT c.comment_id,c.comment_content,c.is_shield,u.user_id,u.user_nickname,c.created_at FROM t_comment c INNER JOIN t_user u
         ON c.assuage_grief_id = :assuage_grief_id AND c.comment_level = '1' AND c.is_delete='1' AND c.user_id = u.user_id ORDER BY c.created_at ASC`;
        const resultComment: any = await this.ctx.model.query(queryStr,
            {
                type: this.ctx.model.QueryTypes.SELECT,
                replacements: { assuage_grief_id: param.assuage_grief_id }
            }
        )
        let returnData: any = [];
        for (let i = 0; i < resultComment.length; i++) {
            let item: any = {};
            item.comment_id = resultComment[i].comment_id;
            item.comment_content = resultComment[i].comment_content;
            item.is_shield = resultComment[i].is_shield;
            item.user_id = resultComment[i].user_id;
            item.user_nickname = resultComment[i].user_nickname;
            item.created_at = resultComment[i].created_at;
            const queryStr1 = `SELECT c.comment_id,c.comment_content,c.is_shield,u.user_id,u.user_nickname,ul.user_id AS target_user_id,ul.user_nickname AS target_user_nickname,c.created_at`
                + ` FROM t_comment c INNER JOIN t_user u ON c.assuage_grief_id = :assuage_grief_id AND c.comment_parent_id = :comment_id AND c.comment_level = '2'`
                + ` AND c.is_delete = '1' AND c.user_id = u.user_id LEFT JOIN t_user ul ON c.target_user_id = ul.user_id ORDER BY c.created_at ASC`
            const resultCommentLevel2: any = await this.ctx.model.query(queryStr1,
                {
                    type: this.ctx.model.QueryTypes.SELECT,
                    replacements: { assuage_grief_id: param.assuage_grief_id, comment_id: item.comment_id }
                }
            )
            item.commentList = resultCommentLevel2;
            returnData.push(item);
        }
        if (returnData.length <= 0) {
            throw new Error(JSON.stringify({ code: 2, msg: '没有数据' }));
        }
        return returnData;
    }

    /**
     * 操作评论状态（1：解除屏蔽，2：屏蔽）
     * @param param 
     */
    public async editCommentShield(param: any) {
        const result = await this.ctx.model.Comment.update({ is_shield: param.type }, { where: { comment_id: param.comment_id } });
        if (result[0] <= 0) {
            throw new Error(JSON.stringify({ code: 2, msg: '操作失败' }));
        }
    }

    /**
     * 评论回复
     * @param param 
     */
    public async commentReply(param: any) {
        const level = Number(param.level);
        const tran = await this.ctx.model.transaction();
        try {
            if (level === 1) {
                const submitData: any = {};
                submitData.comment_id = this.ctx.helper.genUUID();
                submitData.user_id = param.user_id;
                submitData.assuage_grief_id = param.assuage_grief_id;
                submitData.comment_content = param.comment_content;
                submitData.comment_praise = 0;
                submitData.comment_reply = 0;
                submitData.comment_level = param.level;
                submitData.comment_status = param.comment_status;
                submitData.be_comment_status = param.be_comment_status;
                submitData.is_shield = '1';
                submitData.is_delete = '1';
                await this.ctx.model.Comment.create(submitData, { transaction: tran });
                const resultAssuageGrief: any = await this.ctx.model.AssuageGrief.findOne<AssuageGrief>({ attributes: ['assuage_grief_comment'], where: { assuage_grief_id: param.assuage_grief_id }, transaction: tran });
                if (!resultAssuageGrief) {
                    throw new Error(JSON.stringify({ code: 1, msg: '没有找到该解忧' }));
                }
                let assuage_grief_comment = resultAssuageGrief.assuage_grief_comment;
                if (assuage_grief_comment == null || assuage_grief_comment.length === 0) {
                    assuage_grief_comment = 0;
                } else {
                    assuage_grief_comment += 1;
                }
                await this.ctx.model.AssuageGrief.update({ assuage_grief_comment }, { where: { assuage_grief_id: param.assuage_grief_id }, transaction: tran });
            } else if (level === 2) {
                const target_user_id = param.target_user_id;
                if (!target_user_id) {
                    const submitData: any = {};
                    submitData.comment_id = this.ctx.helper.genUUID();
                    submitData.user_id = param.user_id;
                    submitData.assuage_grief_id = param.assuage_grief_id;
                    submitData.comment_parent_id = param.comment_parent_id;
                    submitData.comment_content = param.comment_content;
                    submitData.comment_praise = 0;
                    submitData.comment_reply = 0;
                    submitData.comment_level = param.level;
                    submitData.comment_status = param.comment_status;
                    submitData.be_comment_status = param.be_comment_status;
                    submitData.is_shield = '1';
                    submitData.is_delete = '1';
                    await this.ctx.model.Comment.create(submitData, { transaction: tran });
                    const resultComment: any = await this.ctx.model.Comment.findOne<Comment>({ attributes: ['comment_reply'], where: { comment_id: param.comment_parent_id } });
                    if (!resultComment) {
                        throw new Error(JSON.stringify({ code: 1, msg: '没有找到该评论' }));
                    }
                    let comment_reply = resultComment.comment_reply;
                    if (comment_reply == null || comment_reply.length === 0) {
                        comment_reply = 1;
                    } else {
                        comment_reply += 1;
                    }
                    await this.ctx.model.Comment.update({ comment_reply }, { where: { comment_id: param.comment_parent_id }, transaction: tran });
                } else {
                    const submitData: any = {};
                    submitData.comment_id = this.ctx.helper.genUUID();
                    submitData.user_id = param.user_id;
                    submitData.target_user_id = target_user_id;
                    submitData.assuage_grief_id = param.assuage_grief_id;
                    submitData.comment_parent_id = param.comment_parent_id;
                    submitData.comment_content = param.comment_content;
                    submitData.comment_praise = 0;
                    submitData.comment_reply = 0;
                    submitData.comment_level = param.level;
                    submitData.comment_status = param.comment_status;
                    submitData.be_comment_status = param.be_comment_status;
                    submitData.is_shield = '1';
                    submitData.is_delete = '1';
                    await this.ctx.model.Comment.create(submitData, { transaction: tran });
                    const resultComment: any = await this.ctx.model.Comment.findOne<Comment>({ attributes: ['comment_reply'], where: { comment_id: param.comment_parent_id } });
                    if (!resultComment) {
                        throw new Error(JSON.stringify({ code: 1, msg: '没有找到该评论' }));
                    }
                    let comment_reply = resultComment.comment_reply;
                    if (comment_reply == null || comment_reply.length === 0) {
                        comment_reply = 1;
                    } else {
                        comment_reply += 1;
                    }
                    await this.ctx.model.Comment.update({ comment_reply }, { where: { comment_id: param.comment_parent_id }, transaction: tran });
                }
            }
            await tran.commit();
        } catch (e) {
            await tran.rollback();
            this.ctx.logger.error(e);
            throw new Error(JSON.stringify({ code: 2, msg: '评论失败' }));
        }
    }
}
export default CommentService;